#include "button.h"
#include <basic.h>
#include <gpio.h>
#include <timer.h>

#if !BUTTON_ONLY_USE_BUTTON_SIMPLE_CLICK

#define TO_TIMER_TICK(x) (x / 1)
#define BUTTON_PRESSED_TIME_MIN TO_TIMER_TICK(20)  // 20ms
#define BUTTON_PRESSED_TIME_MAX TO_TIMER_TICK(300) // 300ms

static void buttonFlexCallBack(button_handle_t *handle)
{
    if (NULL == handle)
        return;
}
#endif

button_handle_t *buttonInit(button_handle_t *handle, GPIO_Port port, GPIO_Pin pin, callback_func_t cb, void *user_arg)
{
    GPIO_Init(port, pin, GPIO_MODE_OPEN_DRAIN);

    handle->port = port;
    handle->pin = pin;
    handle->cb.func = cb;
    handle->cb.user_param = user_arg;
    handle->low_count = 0;

    return handle;
}
int8_t buttonDetect(button_handle_t *handle)
{
#if BUTTON_ONLY_USE_BUTTON_SIMPLE_CLICK
    if (GPIO_STATE_LOW == GPIO_Get(handle->port, handle->pin))
    {
        delay(10);

        if (GPIO_STATE_LOW == GPIO_Get(handle->port, handle->pin))
        {
            while (GPIO_STATE_LOW == GPIO_Get(handle->port, handle->pin))
                ;

            if (handle->cb.func != NULL)
            {
                handle->cb.func(handle->cb.user_param);
            }
            return 1;
        }
    }
#else

    if (GPIO_Get(handle->port, handle->pin) == GPIO_STATE_LOW)
    {
        handle->low_count++;

        if (handle->low_count > BUTTON_PRESSED_TIME_MIN)
        {
            if (handle->state == BUTTON_STATE_PRESSED)
                return;

            handle->state = BUTTON_STATE_PRESSED;
            if (handle->cb.func != NULL)
                handle->cb.func(handle->cb.user_param);
        }
    }
    else
    {
        handle->low_count = 0;
        handle->state = BUTTON_STATE_RELEASED;
    }
#endif

    return 0;
}
